package com.senjoeson.teamfriends.activity;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatSpinner;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;

import com.baidu.location.Address;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.model.LatLng;
import com.senjoeson.teamfriends.R;
import com.senjoeson.teamfriends.adapter.MySpinnerAdapter;
import com.senjoeson.teamfriends.base.App;
import com.senjoeson.teamfriends.bean.School;
import com.senjoeson.teamfriends.bean.User;
import com.senjoeson.teamfriends.utils.ALog;
import com.senjoeson.teamfriends.utils.MyToast;
import com.senjoeson.teamfriends.utils.ResourcesUtils;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.listener.UploadFileListener;


/**
 * @author senjoeson
 * @date 2018/4/25
 */

public class UserInfoActivity extends AppCompatActivity implements View.OnClickListener, CompoundButton.OnCheckedChangeListener, AdapterView.OnItemSelectedListener {


    private static final int IMAGE_REQUEST_CODE = 101;
    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.nickname)
    EditText mNickname;
    @BindView(R.id.tel)
    EditText mTel;
    @BindView(R.id.wechat)
    EditText mWechat;
    @BindView(R.id.male)
    RadioButton mMale;
    @BindView(R.id.female)
    RadioButton mFemale;
    @BindView(R.id.cityspinner)
    AppCompatSpinner mCityspinner;
    @BindView(R.id.schoolspinner)
    AppCompatSpinner mSchoolspinner;
    @BindView(R.id.movie)
    CheckBox mMovie;
    @BindView(R.id.food)
    CheckBox mFood;
    @BindView(R.id.trip)
    CheckBox mTrip;
    @BindView(R.id.study)
    CheckBox mStudy;
    @BindView(R.id.goout)
    CheckBox mGoout;
    @BindView(R.id.games)
    CheckBox mGames;
    @BindView(R.id.curious)
    CheckBox mCurious;
    @BindView(R.id.sign)
    EditText mSign;
    @BindView(R.id.confirm)
    Button mConfirm;
    @BindView(R.id.portrait)
    ImageView mPortrait;
    @BindView(R.id.location)
    TextView mLocation;

    private boolean isMan = true;
    private HashMap<String, Boolean> mHashMap = new HashMap<>();
    public String[] cityList;

    private String portraitPath;

    //声明AMapLocationClient类对象
    public LocationClient mLocationClient = null;
    public LatLng mLatLng;

    private MyLocationListener mMyLocationListener = new MyLocationListener();
    public Address mAddress;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_userinfo);
        ButterKnife.bind(this);
        setSupportActionBar(mToolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }
        initDataForSpinner();
        //初始化定位
        mLocationClient = new LocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.registerLocationListener(mMyLocationListener);
        LocationClientOption locationClientOption = new LocationClientOption();
        locationClientOption.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        locationClientOption.setCoorType("bd09ll");
        locationClientOption.setScanSpan(1000);
        locationClientOption.setOpenGps(true);
        locationClientOption.setIsNeedAddress(true);
        locationClientOption.setLocationNotify(true);
        locationClientOption.setIgnoreKillProcess(false);
        locationClientOption.SetIgnoreCacheException(false);
        locationClientOption.setEnableSimulateGps(false);
        mLocationClient.setLocOption(locationClientOption);
        mLocationClient.start();
        mMale.setOnClickListener(this);
        mFemale.setOnClickListener(this);
        mConfirm.setOnClickListener(this);
        mPortrait.setOnClickListener(this);

        mMovie.setOnCheckedChangeListener(this);
        mFood.setOnCheckedChangeListener(this);
        mTrip.setOnCheckedChangeListener(this);
        mStudy.setOnCheckedChangeListener(this);
        mGoout.setOnCheckedChangeListener(this);
        mGames.setOnCheckedChangeListener(this);
        mCurious.setOnCheckedChangeListener(this);
        mLocation.setOnClickListener(this);
        mCityspinner.setOnItemSelectedListener(this);
        mSchoolspinner.setOnItemSelectedListener(this);


    }

    /**
     * 给城市下拉选择器设置数据
     */
    private void initDataForSpinner() {
        MySpinnerAdapter mySpinnerAdapter = new MySpinnerAdapter(App.getContext());
        cityList = ResourcesUtils.getStringArray(R.array.cityList);
        mySpinnerAdapter.setDatas(Arrays.asList(cityList));
        mCityspinner.setAdapter(mySpinnerAdapter);

        ALog.d(cityList[mCityspinner.getSelectedItemPosition()]);
        getSchoolFromProvince(cityList[mCityspinner.getSelectedItemPosition()]);
    }

    /**
     * 从城市中获取学校名称
     *
     * @param city 城市
     */
    private void getSchoolFromProvince(String city) {
        BmobQuery<School> schoolBmobQuery = new BmobQuery<>();
        schoolBmobQuery.addWhereEqualTo("city", city);
        schoolBmobQuery.findObjects(new FindListener<School>() {
            @Override
            public void done(List<School> list, BmobException e) {

                if (e == null) {
                    ArrayList<String> schools = new ArrayList<>();
                    for (School school : list) {
                        schools.add(school.getSchoolname());
                    }
                    MySpinnerAdapter mySchoolSpinnerAdapter = new MySpinnerAdapter(App.getContext());
                    mySchoolSpinnerAdapter.setDatas(schools);
                    mSchoolspinner.setAdapter(mySchoolSpinnerAdapter);
                } else {
                    MyToast.showToast(e.toString());
                }


            }
        });
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            //重写ToolBar返回按钮的行为，防止重新打开父Activity重走生命周期方法
            case android.R.id.home: //返回键
                MyToast.showToast("请填写完整信息，才能回到首页哦！");
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.male:
                isMan = true;
                mMale.setChecked(true);
                mFemale.setChecked(false);
                break;
            case R.id.female:
                isMan = false;
                mFemale.setChecked(true);
                mMale.setChecked(false);
                break;
            case R.id.confirm:
                checkInfo();
                break;
            case R.id.portrait:
                pickPortrait();
                break;
            case R.id.location:
                mLocationClient.start();
                break;

        }
    }

    /**
     * 从相册中获取头像
     */
    private void pickPortrait() {
        Matisse.from(UserInfoActivity.this)
                .choose(MimeType.allOf())
                .countable(true)
                .maxSelectable(1)
                //.addFilter(new GifSizeFilter(320, 320, 5 * Filter.K * Filter.K))
                //.gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .thumbnailScale(0.85f)
                .imageEngine(new GlideEngine())
                .forResult(IMAGE_REQUEST_CODE);

    }

    List<Uri> mSelected;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == IMAGE_REQUEST_CODE && resultCode == RESULT_OK) {
            mSelected = Matisse.obtainResult(data);
            Uri uri = mSelected.get(0);
            mPortrait.setImageURI(uri);
            portraitPath = getPath(uri);
            ALog.d("mSelected: " + portraitPath);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 通过uri获取图片路径
     *
     * @param uri
     * @return
     */
    private String getPath(Uri uri) {
        String[] projection = {MediaStore.Video.Media.DATA};
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }


    /**
     * 检查信息完整
     */
    private void checkInfo() {
        mLocationClient.stop();
        final String nickName = mNickname.getText().toString().trim();
        final String telPhone = mTel.getText().toString().trim();
        final String wechatNumber = mWechat.getText().toString().trim();
        final String city = (String) mCityspinner.getSelectedItem();
        final String schoolName = (String) mSchoolspinner.getSelectedItem();
        if (TextUtils.isEmpty(nickName) || TextUtils.isEmpty(wechatNumber) || TextUtils.isEmpty(telPhone)) {
            MyToast.showToast("所填信息不能为空");
            return;
        }
        if (TextUtils.isEmpty(city) || TextUtils.isEmpty(schoolName)) {
            MyToast.showToast("城市或学校不能为空哦");
            return;
        }
        if (enCountNum(mHashMap) > 3) {
            MyToast.showToast("爱好只能选三个哦！~");
            return;
        } else if (enCountNum(mHashMap) < 3) {
            MyToast.showToast("爱好需要选三个哦");
            return;
        }
        final String personSign = mSign.getText().toString().trim();

        final User currentUser = BmobUser.getCurrentUser(User.class);
        if (TextUtils.isEmpty(portraitPath)) {
            MyToast.showToast("您还没有设置头像");
            return;
        }
        if (mLatLng == null) {
            MyToast.showToast("检测到未获取定位信息，请手动打开定位！");
            return;
        }
        final BmobFile bmobFile = new BmobFile(new File(portraitPath));
        bmobFile.upload(new UploadFileListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    currentUser.setPortrait(bmobFile);
                    currentUser.setNickname(nickName);
                    currentUser.setGender(isMan ? "男" : "女");
                    currentUser.setTelephone(telPhone);
                    currentUser.setWeChat(wechatNumber);
                    currentUser.setCity(city);
                    currentUser.setSchool(schoolName);
                    currentUser.setHobbies(new ArrayList<>(mHashMap.keySet()));
                    currentUser.setSign(personSign);
                    currentUser.setLatLng(mLatLng);
                    currentUser.setAddfriendflag(false);
                    currentUser.update(new UpdateListener() {
                        @Override
                        public void done(BmobException e) {
                            if (e == null) {
                                startActivity(new Intent(UserInfoActivity.this, MainActivity.class));
                                MyToast.showToast("提交成功");
                                ALog.d("更新成功");
                                finish();
                            } else {
                                MyToast.showToast(e.toString());
                            }
                        }
                    });
                } else {
                    MyToast.showToast(e.toString());
                }
            }
        });


    }


    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

        String content = buttonView.getText().toString().trim();
        mHashMap.put(content, isChecked);

    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        switch (parent.getId()) {
            case R.id.schoolspinner:
                String selectedItem = (String) mSchoolspinner.getSelectedItem();
                ALog.d(selectedItem);
                break;
            case R.id.cityspinner:
                getSchoolFromProvince(cityList[position]);
                break;
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }


    /**
     * 计算当前有几个被选中
     *
     * @param hashMap 被计算的hasmap
     * @return 返回结果
     */
    public int enCountNum(HashMap<String, Boolean> hashMap) {
        int count = 0;
        Collection<Boolean> values = hashMap.values();
        for (Boolean value : values) {
            if (value) {
                count++;
            }
        }
        return count;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mLocationClient != null) {
            mLocationClient.stop();
            mLocationClient.unRegisterLocationListener(mMyLocationListener);
        }
    }

    /**
     * 监听位置的信息
     */
    private class MyLocationListener implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location != null) {
                double latitude = location.getLatitude();    //获取纬度信息
                double longitude = location.getLongitude();    //获取经度信息
                mLatLng = new LatLng(latitude, longitude);
                //  Address mAddress = location.getAddress();
                mLocation.setText(location.getAddrStr());
                ALog.d(location.getAddrStr());
                if (location.getAddrStr() != null) {
                    mLocationClient.stop();
                }
            }


        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }
}
